package com.chenjinyan.user.service.impl;

import com.chenjinyan.user.dao.UserRepository;
import com.chenjinyan.user.entity.UserEntity;
import com.chenjinyan.user.service.UserService;
import com.chenjinyan.user.vo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 *
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserRepository userRepository;
    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @PersistenceContext
    private EntityManager em;


    @Override
    public int insertUser(User user) throws ParseException {
        String loginAccount = user.getUsername();
        String password = user.getPassword();
        password = bCryptPasswordEncoder.encode(password);
        String phone = user.getPhone();
        String netName = user.getNetName();
        String birthday = user.getBirthday();
        Date birthdayD = null;
        if (null != birthday && !"".equals(birthday)) {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            birthdayD = formatter.parse(birthday);
        }
        String email = user.getEmail();
        Integer province = user.getProvince();
        Integer city = user.getCity();
        Integer district = user.getDistrict();
        String name = user.getName();

        List<UserEntity> list = userRepository.findByloginAccountOrPhoneOrEmail(loginAccount, phone, email);
        if (null != list && list.size() > 0) {
            //已有用户返回-1
            return -1;
        }

        return userRepository.insertUser(loginAccount, password, netName, phone, birthdayD, email, name, new Date(), province, city, district);

    }

    @Override
    @Transactional(rollbackOn = Exception.class)
    public int updateUser(User user) {
        StringBuilder sqlB = buildSqlForUpdate(user);
        String sql = sqlB.toString();
        String sql1 = sql.substring(0, sql.lastIndexOf(","));
        String sql2 = sql.substring(sql.lastIndexOf(",") + 1);
        Query q = em.createNativeQuery(sql1 + sql2);
        return q.executeUpdate();
    }

    @Override
    public int checkByLoginAcc(String loginAccount) {
        List<UserEntity> list = userRepository.findByloginAccount(loginAccount);
        if (null != list && list.size() > 0) {
            //已有用户返回-1
            return -1;
        }
        return 0;
    }

    @Override
    public int checkByPhone(String loginAccount) {
        List<UserEntity> list = userRepository.findByPhone(loginAccount);
        if (null != list && list.size() > 0) {
            //已有用户返回-1
            return -1;
        }
        return 0;
    }

    @Override
    public int checkByEmail(String loginAccount) {
        List<UserEntity> list = userRepository.findByEmail(loginAccount);
        if (null != list && list.size() > 0) {
            //已有用户返回-1
            return -1;
        }
        return 0;
    }

    @Override
    public List<UserEntity> getUserInfo(Long id) throws ParseException {
        return userRepository.findById(id);
    }

    @Override
    public UserEntity findById(Long id) {
        List<UserEntity> list = userRepository.findById(id);
        if (null == list || list.size() != 1) {
            return null;
        } else {
            return list.get(0);
        }
    }

    @Override
    public int findByUsernameAndPassword(String username, String password) {
        List<UserEntity> list = userRepository.findByloginAccountAndPassword(username, password);
        if (null != list && list.size() > 0) {
            //已有用户返回-1
            return 0;
        }
        return -1;
    }

    @Override
    public int updateLoginTime(String username) {
        return userRepository.updateLoginTime(username);
    }


    private StringBuilder buildSqlForUpdate(User user) {
        StringBuilder sql = new StringBuilder(500);
        sql.append("update ")
                .append("lost_and_find_user set ");

        if (null != user.getUsername() && !"".equals(user.getUsername())) {
            sql.append("LOGIN_ACCOUNT = '" + user.getUsername() + "', ");
        }

        if (null != user.getPassword() && !"".equals(user.getPassword())) {
            String password = user.getPassword();
            password = bCryptPasswordEncoder.encode(password);
            sql.append("PASSWORD = '" + password + "', ");
        }
        if (null != user.getNetName() && !"".equals(user.getNetName())) {
            sql.append("NET_NAME = '" + user.getNetName() + "', ");
        }
        if (null != user.getPhone() && !"".equals(user.getPhone())) {
            sql.append("PHONE = '" + user.getPhone() + "', ");
        }
        if (null != user.getBirthday() && !"".equals(user.getBirthday())) {
            sql.append("BIRTHDAY = '" + user.getBirthday() + "', ");
        }
        if (null != user.getEmail() && !"".equals(user.getEmail())) {
            sql.append("EMAIL = '" + user.getEmail() + "', ");
        }
        if (null != user.getName() && !"".equals(user.getName())) {
            sql.append("NAME = '" + user.getName() + "', ");
        }
        if (null != user.getProvince()) {
            sql.append("PROVINCE = '" + user.getProvince() + "', ");
        }
        if (null != user.getCity()) {
            sql.append("CITY = '" + user.getCity() + "', ");
        }
        if (null != user.getDistrict()) {
            sql.append("DISTRICT = '" + user.getDistrict() + "', ");
        }
        sql.append(" where id = " + user.getId());
        return sql;
    }
}
